import re
from rest_framework import status
from rest_framework.generics import ListAPIView, RetrieveUpdateAPIView, CreateAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from question.models import Question, Answer
from question.serializers import QuestionListSerializer, AnswerSerializer, QuestionDetailSerializer, \
    QuestionCreateSerializer, QuestionUpdateSerializer, AnswerUpdateSerializer
import logging

logger = logging.getLogger('django')


class QuestionListNewView(ListAPIView):
    """列表页最新回答"""
    queryset = Question.objects.all().order_by('-create_time')
    serializer_class = QuestionListSerializer


class QuestionListHotView(ListAPIView):
    """列表页最热回答"""
    queryset = Question.objects.all().order_by('-click_count')
    serializer_class = QuestionListSerializer


class QuestionListWaitView(ListAPIView):
    """列表页等待回答"""
    queryset = Question.objects.filter(answer_count=0)
    serializer_class = QuestionListSerializer


class QuestionDetailView(RetrieveUpdateAPIView):
    """问答详情页"""
    serializer_class = QuestionDetailSerializer

    def get_object(self):
        question_id = self.kwargs['pk']
        return Question.objects.get(id=question_id)


class QuestionCreateView(CreateAPIView):
    """问题提交页"""

    serializer_class = QuestionCreateSerializer

    # permission_classes = [IsAuthenticated]
    def create(self, request, *args, **kwargs):
        # print(request.data) # {'content': '<p>问题内容11111</p>\n', 'title': '问题标题555', 'label': 'php'}
        content = request.data.get('content', "")
        title = request.data.get('title', "")
        label = request.data.get('label', "")
        author = request.data.get('author')
        try:
            label_list = re.split('[,;]', label)
        except Exception as e:
            logger.error(e)
            raise
        labels = []
        for i in label_list:
            labels.append({'name': i})
        data_dict = {"content": content, "title": title, "labels": labels, "author": author}
        serializer = self.get_serializer(data=data_dict)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class QuestionUpdateView(UpdateAPIView):
    """问题点赞"""
    serializer_class = QuestionUpdateSerializer

    def get_object(self):
        question_id = self.kwargs['question_id']
        return Question.objects.get(id=question_id)


class AnswerView(ListAPIView):
    """答案展示"""
    serializer_class = AnswerSerializer

    def get_queryset(self):
        question_id = self.kwargs['question_id']
        answer_list = Answer.objects.filter(question_id=question_id)
        return answer_list


class AnswerUpdateView(UpdateAPIView):
    """答案点赞"""
    serializer_class = AnswerUpdateSerializer

    def get_object(self):
        answer_id = self.kwargs['answer_id']
        return Answer.objects.get(id=answer_id)
